package com.gongj.hystrix.service;

import com.gongj.commons.pojo.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCollapser;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Future;

/**
 * @program: cloudlx
 * @description:
 * @author: gongj
 * @Description: TODO
 * @create: 2020-06-19 15:39
 **/
@Service
public class UserService {

    @Autowired
    RestTemplate restTemplate;

    // 使用注解实现请求合并
    @HystrixCollapser(batchMethod = "getUsersByIds2",collapserProperties =
            {@HystrixProperty(name = "timerDelayInMilliseconds",value = "2000"),
             //设置触发批处理执行之前，在批处理中允许的最大请求数。
             @HystrixProperty(name = "maxRequestsInBatch", value = "20")
            }
            ,scope = com.netflix.hystrix.HystrixCollapser.Scope.GLOBAL)
    public Future<User> getUserById(String id) {
        return null;
    }

    @HystrixCommand
    public List<User> getUsersByIds2(List<String> ids) {
        System.out.println("合并请求：" + Thread.currentThread().getName() + " ===》 " + ",ids=" + ids);
        User[] users = restTemplate.getForObject("http://appUser/api/user/getUserByIds/{1}", User[].class, StringUtils.join(ids, ","));
        return Arrays.asList(users);
    }



    // 继承的方式实现请求合并
    public List<User> getUsersByIds(List<String> ids) {
        System.out.println("合并请求：" + Thread.currentThread().getName() + "====,ids=" + ids);
        User[] users = restTemplate.getForObject("http://appUser/api/user/getUserByIds/{1}", User[].class, StringUtils.join(ids, ","));
        return Arrays.asList(users);
    }
}
